package com.sunday.gateway.mock.security.webflux.login.handler;

import com.sunday.common.core.enums.ErrorCodeEnum;
import com.sunday.common.core.remoting.rest.response.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

@Slf4j
public class JsonServerAccessDeniedHandler implements ServerAccessDeniedHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {

        RestResponse<String> restResponse = RestResponse.error(ErrorCodeEnum.A0_301, RestResponse.ShowTypeEnum.SILENT);

        log.info("拒绝访问 url : {} , error : {}", exchange.getRequest().getURI().getPath(), denied.toString());
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.FORBIDDEN);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer buffer = dataBufferFactory.wrap(restResponse.toJson().getBytes(Charset.defaultCharset()));
        return response.writeWith(Mono.just(buffer)).doOnError((_) -> DataBufferUtils.release(buffer));
    }

}
